#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   MqttThread.py
@Time    :   2020/07/13 10:31:10
@Author  :   Xiong qiufeng
@Version :   1.0
@Contact :   1528399071@qq.com
@License :   (C)Copyright 2017-2018, Liugroup-NLPR-CASIA
@Desc    :   None
'''

from common.libs.Log import logger

from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

import paho.mqtt.client as mqtt
import paho.mqtt.subscribe as subscribe
import paho.mqtt.publish as publish

import time, threading

class MqttThread(QLabel):

    signal_on_message = pyqtSignal(str, str, str)
    signal_on_connect = pyqtSignal()
    signal_on_disconnect = pyqtSignal()
    signal_on_subscribe = pyqtSignal()

    signal_log = pyqtSignal(dict)

    conf = {}
    client = None
    running = False
    is_connect = False
    auto_connect = False

    def __init__(self):
        super(QLabel, self).__init__()
        self._thread = threading.Thread(target=self.run)
        self._thread.daemon = True
        self._thread.start()

    def load_conf(self, conf):
        """加载配置"""
        self.conf = conf
        self.auto_connect = self.conf['auto_connect']
        self.client = mqtt.Client(client_id=self.conf['client_id'])
        self.client.on_connect = self.on_connect
        self.client.on_disconnect = self.on_disconnect
        self.client.on_subscribe = self.on_subscribe
        self.client.on_message = self.on_message
        self.client.connect(self.conf['host'], self.conf['port'], self.conf['keep_alive'])
        self.client.enable_logger(logger)
        self.client.loop_start()

    def do_subscribe(self, topics):
        """订阅"""
        if self.is_connect:
            self.client.subscribe(topics)

    def do_publish(self, topic, payload, qos):
        """推送消息"""
        if self.is_connect:
            self.client.publish(topic, payload, int(qos))

    def on_subscribe(self, client, obj, mid, granted_qos):
        """订阅通知"""
        self.signal_on_subscribe.emit()

    def on_connect(self, mqttc, obj, flags, rc):
        """连接通知"""
        if rc == 0:
            self.is_connect = True
            self.signal_on_connect.emit()
    
    def on_disconnect(self, mqttc, obj, rc):
        """断开通知"""
        self.is_connect = False
        self.running = False
        self.signal_on_disconnect.emit()
        print(obj)
        if self.auto_connect:
            logger.info("mqtt断开重连...")
            self.client.reconnect()

    def on_message(self, mqttc, obj, msg):
        """接收消息通知"""
        self.signal_on_message.emit(msg.topic, str(msg.payload.decode()), str(msg.qos))

    def start(self):
        self.running = True

    def stop(self):
        """关闭线程"""
        # logger.info('断开连接')
        self.running = False
        if self.client:
            self.is_connect = False
            self.client.loop_stop()
            self.signal_on_disconnect.emit()

    def run(self):
        """运行"""
        # logger.info("连接mqtt")
        # self.client.loop_forever()
        while self.running:
            # self.client.loop_forever()
            if self.client:
                self.client.loop()

